

import { LocalTable } from "./LocalTable";
export class Sqlite3Storage extends LocalTable {


    updateItemByKey(key: string, value: any) {
        let sqlStr = 'update ' + this.tbName + ' set value = ? where id=?';
        return this.setData(sqlStr, value, key)
    }

    insertItemByKey(key: string, value: any) {
        var sqlStr = 'INSERT INTO ' + this.tbName + ' ' + this._tableParser.insertStr;
        return this.setData(sqlStr, key, value)
    }

    getItem(key: string) {
        return new Promise((reslove: Function, reject: Function) => {
            var sqlStr = 'select value  from ' + this.tbName + ' where id = ?';
            this.getData(sqlStr, key).then((row) => {
                // console.log(" getItem ", row)
                reslove(row)
            })
        })

    }

    setItem(key: string, value: any) {
        return new Promise((reslove: Function, reject: Function) => {
            var sqlStr = 'select value  from ' + this.tbName + ' where id=?';
            this.getData(sqlStr, key).then((row) => {
                // console.log(" setItem ", row)
                if (row) {
                    this.updateItemByKey(key, value).then((code: number) => {
                        reslove(code)
                    })
                } else {
                    this.insertItemByKey(key, value).then((code: number) => {
                        reslove(code)
                    })
                }
            })
        })
        // console.log(" setItem key ", key, 'value', value)


    }

    removeItem(key: string) {
        return new Promise((reslove: Function, reject: Function) => {
            var sqlStr = 'delete from ' + this.tbName + '  where id=?';
            this.setData(sqlStr, key).then(() => {
                reslove()
            })
        })

    }

    insertAll(list: any[]) {
        var sqlStr = 'INSERT INTO ' + this.tbName + ' (id,value) VALUES (@id, @value)';
        return this.transactionData(sqlStr, list)
    }

    updateAll(list: any[]) {
        var sqlStr = 'update ' + this.tbName + ' set value=@value where id=@id';
        return this.transactionData(sqlStr, list)
    }

    deleteAll(list: any[]) {
        var sqlStr = 'delete from ' + this.tbName + ' where id=@id';
        return this.transactionData(sqlStr, list)
    }
}